<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #editor{
      border: 1px solid #ccc;
      padding: 10px;
      min-height: 200px;
      max-height: 400px;
      overflow-y: auto;
    }
  </style>
</head>
<body>
  <button onclick="wrapSelection('strong')">加粗</button>
  <button onclick="wrapSelection('em')">斜体</button>
  <button onclick="wrapSelection('u')">下划线</button>
  <div id="editor" contenteditable="true"></div>
</body>
<script>
  function wrapSelection(tagName){
    const selection = window.getSelection();
    if(!selection.rangeCount) return;

    const range = selection.getRangeAt(0)
    if(range.collapsed){
      alert("请先选择一些文本");
      return;
    }

    const wrapper = document.createElement(tagName);
    const selectionContent = range.extractContents();

    wrapper.appendChild(selectionContent);

    range.insertNode(wrapper);

    const newRange = document.createRange();
    newRange.setStartAfter(wrapper);
    newRange.collapse(true);

    selection.removeAllRanges();
    selection.addRange(newRange);
  }
</script>
</html>